package com.tgy.leetcode;

/**
 * @Author: tgy
 * @Date: 12/24/20 4:11 PM
 *
 *  https://leetcode-cn.com/problems/candy/
 */
public class _135_分发糖果_02 {

    public int candy(int[] ratings) {

        if (ratings == null || ratings.length == 0) {

            return 0;
        }

        if (ratings.length == 1) {

            return 1;
        }

        int sum = 1;
        int index = 1,preVal = 1,incNum = 1,decNum = 0;

        while (index < ratings.length) {

            if (ratings[index] >= ratings[index - 1]) {

                decNum = 0;
                preVal = ratings[index] == ratings[index - 1]?1:preVal+1;
                sum += preVal;
                incNum = preVal;
            }else {

                // 注意这里要设置 preVal设置为1，因为再次递增时，最小值从1开始
                preVal = 1;
                decNum++;

                if (decNum == incNum) {

                    decNum++;
                }

                sum += decNum;
            }

            index++;
        }

        return sum;
    }
}


